from __future__ import absolute_import, division, print_function, unicode_literals

import datetime
from backtrader.feed import DataBase
from backtrader import date2num
import SimpleMySqlClass as smc
import json


class MySQLDataFeed(DataBase):
    def __init__(self, load_data_sql):
        self.conn = smc.SimpleMySqlClass("127.0.0.1", "stocks", "haojg", "haojg")
        self.cursor = self.conn.get_cursor()
        self.load_data_sql = load_data_sql
        self.cur_row = []

    def start(self):
        self.result = self.conn.execute(self.load_data_sql)

    def stop(self):
        self.conn.close()
        return

    def get_cur_row(self):
        return self.cur_row

    def _load(self):
        one_row = self.cursor.fetchone()
        self.cur_row = one_row
        if one_row is None:
            return False
        # self.lines.datetime[0] = date2num(
        #     datetime.datetime.strptime(one_row[0], "%Y-%m-%d")
        # )
        self.lines.datetime[0] = date2num(one_row[0])
        self.lines.open[0] = float(one_row[1])
        self.lines.high[0] = float(one_row[2])
        self.lines.low[0] = float(one_row[3])
        self.lines.close[0] = float(one_row[4])
        self.lines.volume[0] = float(one_row[5])
        self.lines.openinterest[0] = -1
        return True
